package net.sky.oa.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sky.oa.model.DocFolder;

public class FolderTreeUtils {
	
	private StringBuffer returnStr = new StringBuffer();
	
	public FolderTreeUtils(List list, DocFolder docFolder)
	{
		recursionFn(list,docFolder);
	}
	
	/**
	 * 递归调用
	 */
	public void recursionFn(List list, DocFolder docFolder) {
		List childList = getChildList(list, docFolder.getId());
		if (childList.size() > 0) {
			returnStr.append("{id:'");
			returnStr.append(docFolder.getId());
			returnStr.append("',text:'");
			returnStr.append(docFolder.getFolderName());
			if(0==docFolder.getId())
			{
				returnStr.append("',expanded:true,iconCls:'menu-file-disk',children:[");
			}else{
				returnStr.append("',expanded:true,iconCls:'menu-file-folder',children:[");
			}
			Iterator it = childList.iterator();
			while (it.hasNext()) {
				DocFolder n = (DocFolder) it.next();
				recursionFn(list, n);
			}
			returnStr.append("]},");
		} else {
			returnStr.append("{id:'");
			returnStr.append(docFolder.getId());
			returnStr.append("',text:'");
			returnStr.append(docFolder.getFolderName());
			if(0==docFolder.getId())
			{
				returnStr.append("',iconCls:'menu-file-disk',leaf:true},");
			}else
			{
				returnStr.append("',iconCls:'menu-file-folder',leaf:true},");
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	public List getChildList(List list, Long parentId) {
		List li = new ArrayList();
		/**
		 * list 作为全局变量， 这里remove所以要线程同步 ，如果不remove则不要线程同步也可。
		 */
		synchronized (list) {
			Iterator it = list.iterator();
			while (it.hasNext()) {
				DocFolder n = (DocFolder) it.next();
				if (parentId .equals(n.getParentId())) {
					li.add(n);
					it.remove(); 
				}
			}
		}
		return li;
	}
	/**
	 * 返回修饰后的Json字符串
	 */
	public String getStr() {
		return ("[" + returnStr + "]").replaceAll(",]", "]");

	}
	
	/*
	public static void main(String[] args) {
		long _start = System.nanoTime();
		FolderTreeUtils tree = new FolderTreeUtils();
		DocFolder folder = new DocFolder();
		folder.setId(0L);
		folder.setFolderName("我的网盘");
		tree.recursionFn(tree.nodeList, folder);
		System.out.println(tree.modifyStr(tree.returnStr.toString()));
		long _end = System.nanoTime();
		System.out.println(_end - _start);
	}
	*/
}
